import Vue from 'vue';
import axios from 'axios';
import router from '../router';

let loading = null;
let messageBox = null;

const baseURL = '';

const axiosConfig = {
    baseURL,
    timeout: 30 * 1000, // Timeout
    // withCredentials: true, // Check cross-site Access-Control
};
const Axios = axios.create(axiosConfig);
// 请求拦截
Axios.interceptors.request.use(
    (config) => {
        window.NProgress.start();
        if (config.loading) {
            loading = Vue.prototype.$loading({
                lock: true,
                text: config.loadingText || '页面加载中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
        }

        return config;
    },
    (error) => {
        window.NProgress.done();
        Promise.reject(error);
    },
);

// 响应拦截
Axios.interceptors.response.use(
    async (res) => {
        window.NProgress.done();
        if (loading) loading.close();

        const { code, message } = res.data || {};

        // 错误提示拦截
        const showMessage = () => {
            const messageTip = message || '服务器响应失败，请稍后再试';
            if (messageBox) messageBox.close();
            messageBox = Vue.prototype.$message.error(messageTip);
        };

        // 返回成功响应
        if (String(code) === '200') return res;

        showMessage();

        // 登录失效拦截
        if (['401', '906'].includes(String(code))) {
            router.push('/login');
            const root = `${window.location.protocol}//${window.location.host}`;
            window.location.replace(`${root}/#/login`);
        }

        return Promise.reject(res);
    },
    (error) => {
        window.NProgress.done();
        if (loading) loading.close();
        if (messageBox) messageBox.close();
        messageBox = Vue.prototype.$message.error('服务器内部异常');
        return Promise.reject(error);
    },
);

window.axios = Axios;
Vue.prototype.$http = Axios;
